package com.fresh.auth.controller;

import com.fresh.auth.Service.PermissionService;
import com.fresh.auth.Service.UserService;
import com.fresh.common.ResponseResult;
import com.fresh.entity.Permission;
import com.fresh.entity.User;
import com.fresh.util.JwtUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/auth")
@RestController
public class AuthenticateController {

    @Autowired
    UserService userService;

    @HystrixCommand(fallbackMethod = "fallback")
    @Cacheable(value = "user")
    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user, HttpServletResponse response){
        User found = userService.login(user);
        if(found != null){
            String token = JwtUtil.create(user.getUserName(),user.getUserId());
            response.setHeader("token",token);
            response.setHeader("Access-Control-Expose-Headers","token");
            return new ResponseResult(200,"ok",token);
        }
        System.out.println("密码错误,登录失败");
        return new ResponseResult(401,"no","login failed");
    }

    @Autowired
    PermissionService permissionService;

    @PostMapping("/author")
    public ResponseResult<Boolean> author(@RequestBody User user){
        Integer uid = userService.getUserId(user);
        List<Permission> permissions = permissionService.getPermissions(uid);
        List<String> permission = new ArrayList<>();
        for (Permission p: permissions) {
            permission.add(p.getPermission());
        }
        System.out.println(user.getUrl());
        System.out.println(user.getMethod());
        String url = user.getUrl();
        String a = url.substring(url.indexOf("/"),url.lastIndexOf("/")+1)
                +":"+user.getMethod();
        boolean flag = false;

        if(permission.contains(a)){
            flag = true;
            System.out.println("鉴权成功");
        }
        return new ResponseResult<Boolean>(200,"success",flag);
    }

    public ResponseResult fallback(@RequestBody User user, HttpServletResponse response) {
        System.out.println("fallback");
        return new ResponseResult(500, "error", "服务器出错，稍后重试" );
    }

    @GetMapping("/getMyInfo")
    public Object getMyInfo(@SessionAttribute User user){
        return new ResponseResult<>(200,"0k",user);
    }

}
